const User = require('../model/users.model')

class UserService {
  // 创建用户/注册
  async createUser(username, password) {
    const res = await User.create({ username, password })
    // 返回注册数据
    return res.dataValues
  }

  // 查询用户信息
  async getUserInfo({ id, username, password, isAdmin }) {
    const whereOpt = { ...arguments[0] }
    // 调用方法查询数据库
    const res = await User.findOne({
      attributes: ['id', 'username', 'password', 'isAdmin'],
      where: whereOpt
    })
    return res ? res.dataValues : null
  }

  // 通过id更新用户信息
  async updataById({ id, username, password, isAdmin }) {
    const whereOpt = { id }
    const newUser = {}
    username && Object.assign(newUser, { username })
    password && Object.assign(newUser, { password })
    isAdmin && Object.assign(newUser, { isAdmin })

    const res = await User.update(newUser, { where: whereOpt })
    // console.log(res, '更新')
    return res[0] > 0
  }
}

module.exports = new UserService() 